import { _decorator, Component, Node, instantiate, AudioSource, AudioClip, Label, assert } from 'cc';
import { StorageUtil } from '../Utils/StorageUtil';
import { ResMgr } from './ResMgr';
const { ccclass, property } = _decorator;

@ccclass('SoundMgr')
export class SoundMgr extends Component {
    public static Instance:SoundMgr = null;
    private _soundAS:AudioSource;
    private _musicAS:AudioSource;
    /**
     * 音效开关状态，true 音效打开中，false 音效关闭
     */
    private _onOffSound: boolean;
    private _onOffMusic: boolean;

    onLoad(){
        if(null === SoundMgr.Instance){
            SoundMgr.Instance = this;
            this._soundAS = this.node.getChildByName("soundAudio").getComponent(AudioSource);
            this._musicAS = this.node.getChildByName("musicAudio").getComponent(AudioSource);
            
        }else{
            this.destroy();
        }

        //
        this.onOffSound = StorageUtil.Instance.getOnOffSound();
        this.onOffMusic = StorageUtil.Instance.getOnOffMusic();
    }
    /**
     * 播放背景音乐
     */
    public playBgMusic():void{
        this.getAudioAsset("bgm", (clip)=>{
            if(null != clip) {
                this._musicAS.clip = clip;
                this._musicAS.loop = true;
                this._musicAS.play();
            }
        });
    }

    /**
     * 音乐
     */
    public get onOffMusic(): boolean {
        return this._onOffMusic;
    }

    /**
     * 音乐
     */
    public set onOffMusic(value: boolean) {
        this._onOffMusic = value;
        //
        if(value){
            this._musicAS.volume = 1.0;
        }else{
            this._musicAS.volume = 0.0;
        }
        StorageUtil.Instance.setOnOffMusic(value);
    }

    /**
     * 音效开关状态，true 音效打开中，false 音效关闭
     */
    public get onOffSound(): boolean {
        return this._onOffSound;
    }

    /**
     * 音效开关状态，true 音效打开中，false 音效关闭
     */
    public set onOffSound(value: boolean) {
        this._onOffSound = value;
        //
        if(value){
            this._soundAS.volume = 1.0;
        }else{
            this._soundAS.volume = 0.0;
        }
        StorageUtil.Instance.setOnOffSound(value);
    }

    public playEffect(name:string, isLoop:boolean=false){
        // if(!this._onOffSound) return;
        //
        this.getAudioAsset(name, (clip)=>{
            if(null != clip) {
                this._soundAS.clip = clip;
                this._soundAS.play();
            }
        });
    }

    public getAudioAsset(name:string, callback:Function):void{
        var asset = ResMgr.Instance.getAsset("Sounds", name);
        if(null != asset){
            if(null != callback) callback(asset);
        }else{
            ResMgr.Instance.loadResByAudioClip("Sounds", name, (asset)=>{
                if(null != callback) callback(asset);
            });
        }
    }
}

